.PHONY : all clean tarball config

PROJECT := dlt

ROOT_DIR = $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
BUILD_DIR := $(ROOT_DIR)/build
INSTALL_DIR := $(BUILD_DIR)/$(PROJECT)
PACKAGE_FILE := $(PROJECT).tgz
ANDROID_DNK := /opt/android-ndk-r23b
CMAKE := cmake

CMAKELISTS_FILES := $(shell find $(ROOT_DIR)/src/ -type f -name 'CMakeLists.txt')
CMAKELISTS_FILES += $(ROOT_DIR)/CMakeLists.txt
MAKEFILE_FILES := $(ROOT_DIR)/Makefile

BUILD_TYPE := RelWithDebInfo
ifeq ($(origin RELEASE), command line)
  ifeq ($(RELEASE), true)
    BUILD_TYPE = Release
  endif
endif

all: config
	@make -C $(BUILD_DIR) all -j$(nproc)

tarball: all
	@-rm -rf $(INSTALL_DIR) $(BUILD_DIR)/$(PACKAGE_FILE)
	@make -C $(BUILD_DIR) install
	@tar -zcf $(BUILD_DIR)/$(PACKAGE_FILE) -C $(BUILD_DIR) $(PROJECT)

config: $(BUILD_DIR)/CMakeCache.txt

$(BUILD_DIR)/CMakeCache.txt: $(CMAKELISTS_FILES) $(MAKEFILE_FILES)
	@echo "-- BUILD_DIR: $(BUILD_DIR)"
	@if [ ! -d $(BUILD_DIR) ]; then mkdir -p $(BUILD_DIR); else rm -f $@; fi
	@$(CMAKE) -B$(BUILD_DIR) \
		   -G "Unix Makefiles" \
		   -DCMAKE_TOOLCHAIN_FILE=$(ANDROID_DNK)/build/cmake/android.toolchain.cmake \
		   -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
		   -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) \
		   -DCMAKE_INSTALL_PREFIX=$(INSTALL_DIR) \
	       -DDLT_IPC=UNIX_SOCKET \
		   -DWITH_UDP_CONNECTION=OFF \
		   -DWITH_MAN=OFF \
		   -DWITH_DLT_SYSTEM=OFF \
		   -DWITH_DLT_DBUS=OFF \
		   -DWITH_DLT_KPI=OFF \
		   -DWITH_DLT_USE_IPv6=OFF \
		   -DWITH_DLT_EXAMPLES=OFF \
		   -DWITH_DLT_TESTS=OFF \
		   -DWITH_DLT_PKGCONFIG=OFF \
		   -DWITH_DLT_CXX11_EXT=ON \
		   -DWITH_DLT_LOGSTORAGE_CTRL_UDEV=OFF \
		   $(ROOT_DIR)
	@ln -f -s $(BUILD_DIR)/compile_commands.json .

clean:
	@echo "Clean up..."
	@-make -C $(BUILD_DIR) clean
	@-rm -rf $(BUILD_DIR)

